package com.wondream.myframework.app.common.aspect;

import com.alibaba.fastjson.JSON;
import com.wondream.myframework.app.common.annotation.ThirdPartAnno;
import com.wondream.myframework.app.common.config.cfsscofl.CoflProperties;
import com.wondream.myframework.app.common.exception.BusinessExeceptionCode;
import com.wondream.myframework.app.common.util.JacksonUtil;
import com.wondream.myframework.app.vo.base.OpRequest;
import org.springframework.core.annotation.AnnotationUtils;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class CheckSignCustomReqRspExtend implements CustomReqRspExtend {

    @Resource
    private CoflProperties coflProperties;

    @Override
    public Object[] transferArg(Method method, Object[] args) {
        // 针对第三方注解
        ThirdPartAnno thirdPartAnno = AnnotationUtils.findAnnotation(method, ThirdPartAnno.class);
        if (null == thirdPartAnno) {
            return args;
        }
        // 获取请求参数的泛型，解密验证后转化为对应的对象
        Type[] types = method.getGenericParameterTypes();
        Type type = types[0];
        if (type instanceof ParameterizedType) {
            Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments();
            Type t = actualTypes[0];
            Object arg = args[0];
            OpRequest request = (OpRequest) arg;
            Object o = null;
            if (coflProperties.isThirdAnnoIgnore()) {
                o = JSON.parseObject(JacksonUtil.toJson(request.getParams()), (Class) t);
            } else {
                // 如果有加密可以对应解密
                o = JSON.parseObject(JacksonUtil.toJson(request.getParams()), (Class) t);
            }
            request.setParams(o);
            args[0] = request;
        } else {
            throw BusinessExeceptionCode.SYS_ERROR.exp();
        }
        return args;
    }
}
